<template>
  <el-dialog
    :title="isEdit ? '编辑评论' : '新增评论'"
    :model-value="visible"
    @close="handleClose"
    width="700px"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="评论内容" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="4"
          placeholder="请输入评论内容"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="选择用户" prop="userId">
        <el-select
          v-model="form.userId"
          placeholder="请选择用户"
          style="width: 100%"
          filterable
          clearable
          :loading="userLoading"
        >
          <el-option
            v-for="user in userList"
            :key="user.id"
            :label="`${user.username} (ID: ${user.id})`"
            :value="user.id"
          >
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <span>{{ user.username }}</span>
              <span style="color: #999; font-size: 12px;">ID: {{ user.id }}</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="选择文章" prop="articleId">
        <el-select
          v-model="form.articleId"
          placeholder="请选择文章"
          style="width: 100%"
          filterable
          clearable
          :loading="articleLoading"
        >
          <el-option
            v-for="article in articleList"
            :key="article.id"
            :label="`${article.title} (ID: ${article.id})`"
            :value="article.id"
          >
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <span style="max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                {{ article.title }}
              </span>
              <span style="color: #999; font-size: 12px;">ID: {{ article.id }}</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="父评论">
        <el-select
          v-model="form.parentId"
          placeholder="请选择父评论（可选）"
          style="width: 100%"
          filterable
          clearable
          :loading="commentLoading"
        >
          <el-option
            v-for="comment in commentList"
            :key="comment.id"
            :label="`${comment.content.substring(0, 30)}... (ID: ${comment.id})`"
            :value="comment.id"
          >
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <span style="max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                {{ comment.content.substring(0, 30) }}{{ comment.content.length > 30 ? '...' : '' }}
              </span>
              <span style="color: #999; font-size: 12px;">ID: {{ comment.id }}</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">
        {{ isEdit ? '更新' : '创建' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { createComment, updateComment } from '@/api/comment'
import { getUserList } from '@/api/user'
import { getArticleList } from '@/api/article'
import { getCommentList } from '@/api/comment'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  comment: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'success'])

const formRef = ref()
const loading = ref(false)
const userLoading = ref(false)
const articleLoading = ref(false)
const commentLoading = ref(false)

// 数据列表
const userList = ref([])
const articleList = ref([])
const commentList = ref([])

const form = reactive({
  content: '',
  userId: '',
  articleId: '',
  parentId: ''
})

const rules = {
  content: [
    { required: true, message: '请输入评论内容', trigger: 'blur' },
    { min: 1, max: 500, message: '评论内容长度在 1 到 500 个字符', trigger: 'blur' }
  ],
  userId: [
    { required: true, message: '请选择用户', trigger: 'change' }
  ],
  articleId: [
    { required: true, message: '请选择文章', trigger: 'change' }
  ]
}

// 获取用户列表
const fetchUserList = async () => {
  try {
    userLoading.value = true
    console.log('开始获取用户列表...')
    const result = await getUserList({ page: 1, size: 100 })
    console.log('用户列表响应:', result)
    if (result.code === 200) {
      userList.value = result.data.records || []
      console.log('用户列表获取成功，数量:', userList.value.length)
    } else {
      console.warn('用户列表响应异常:', result)
      userList.value = []
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    userList.value = []
    // 不显示错误消息，避免影响用户体验
  } finally {
    userLoading.value = false
  }
}

// 获取文章列表
const fetchArticleList = async () => {
  try {
    articleLoading.value = true
    console.log('开始获取文章列表...')
    const result = await getArticleList({ page: 1, size: 100 })
    console.log('文章列表响应:', result)
    if (result.code === 200) {
      articleList.value = result.data.records || []
      console.log('文章列表获取成功，数量:', articleList.value.length)
    } else {
      console.warn('文章列表响应异常:', result)
      articleList.value = []
    }
  } catch (error) {
    console.error('获取文章列表失败:', error)
    articleList.value = []
    // 不显示错误消息，避免影响用户体验
  } finally {
    articleLoading.value = false
  }
}

// 获取评论列表
const fetchCommentList = async () => {
  try {
    commentLoading.value = true
    console.log('开始获取评论列表用于父评论选择...')
    const result = await getCommentList({ page: 1, size: 100 })
    console.log('评论列表响应:', result)
    if (result.code === 200) {
      commentList.value = result.data.records || []
      console.log('评论列表获取成功，数量:', commentList.value.length)
    } else {
      console.warn('评论列表响应异常:', result)
      commentList.value = []
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    commentList.value = []
    // 不显示错误消息，避免影响用户体验
  } finally {
    commentLoading.value = false
  }
}

// 初始化数据
const initData = async () => {
  console.log('开始初始化编辑对话框数据...')
  try {
    // 使用 Promise.allSettled 避免某个API失败影响其他API
    const results = await Promise.allSettled([
      fetchUserList(),
      fetchArticleList(),
      fetchCommentList()
    ])
    console.log('编辑对话框数据初始化完成，结果:', results)
  } catch (error) {
    console.error('初始化数据时出现错误:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    content: '',
    userId: '',
    articleId: '',
    parentId: ''
  })
  formRef.value?.clearValidate()
}

// 监听评论数据变化
watch(() => props.comment, (newVal) => {
  if (newVal && Object.keys(newVal).length > 0) {
    Object.assign(form, {
      content: newVal.content || '',
      userId: newVal.userId || '',
      articleId: newVal.articleId || '',
      parentId: newVal.parentId || ''
    })
  } else {
    resetForm()
  }
}, { immediate: true })

// 监听对话框显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 只在对话框打开时才加载数据，不在页面初始化时加载
    // 延迟初始化，避免阻塞主页面
    setTimeout(() => {
      initData()
    }, 100)
  }
})

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true
    
    const submitData = {
      content: form.content,
      userId: Number(form.userId),
      articleId: Number(form.articleId),
      parentId: form.parentId ? Number(form.parentId) : null
    }
    
    let result
    if (props.isEdit) {
      result = await updateComment(props.comment.id, submitData)
    } else {
      result = await createComment(submitData)
    }
    
    if (result.code === 200) {
      ElMessage.success(props.isEdit ? '更新评论成功' : '创建评论成功')
      emit('success')
      handleClose()
    } else {
      ElMessage.error(result.message || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.el-form {
  .el-form-item {
    margin-bottom: 20px;
  }
}
</style>
